package com.zmn.oms.api.filter;

import com.dianping.cat.servlet.CatFilter;
import com.zmn.common.web.utils.PatternMatcher;
import com.zmn.common.web.utils.ServletPathMatcher;
import com.zmn.common.web.utils.WebUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * @author quanjic
 * @version v1.0
 * @since 2018/12/6 19:37
 **/
public class ZmnCatFilter extends CatFilter {

    public static final String EXCLUSIONS = "exclusions";

    protected PatternMatcher pathMatcher = new ServletPathMatcher();

    private Set<String> excludesPattern;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        super.init(filterConfig);
        String exclusions = filterConfig.getInitParameter(EXCLUSIONS);
        if (exclusions != null && exclusions.trim().length() != 0) {
            excludesPattern = new HashSet<>(Arrays.asList(exclusions.split(",")));
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        if (this.isExclusion(request)) {
            chain.doFilter(request, response);
            return;
        } else {
            super.doFilter(request, response, chain);
        }
    }

    protected boolean isExclusion(ServletRequest request) {

        return WebUtils.isMatchPath((HttpServletRequest) request, excludesPattern, pathMatcher);
    }

}
